package com.latam.arq.example.web.validators;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.NoneScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;



@ManagedBean(name="RutValidator")
@NoneScoped
public class RutValidator implements Validator{
	


	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {	
		String rut = value.toString();
		
		try{
			

			
			String[] rutArray = rut.split("-");
			String rutSdv=rutArray[0];
			String rutDv=rutArray[1];
			
			if(!rutDv.equals(RutValidator.getObtenerDvRut(rutSdv))){
				FacesMessage msg = 	new FacesMessage("ingrese un rut valido", 	"ingrese un rut valido");
				msg.setSeverity(FacesMessage.SEVERITY_ERROR);
				throw new ValidatorException(msg);
			}
			
		}catch(Exception e){
			
			FacesMessage msg = 	new FacesMessage(""+e, ""+e);
			msg.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(msg);
			
		}
		
		

		
	}
	
	public static String getObtenerDvRut(String rut) {
		String rutString = String.valueOf(rut);
		int M=0,S=1,T=Integer.parseInt(rutString);
		  for(;T!=0;T/=10)S=(S+T%10*(9-M++%6))%11;
		return String.valueOf((char)(S!=0?S+47:75));
	}
		
}
